﻿# -*- coding:utf-8 -*-
# 
#  импорт списка отделов ГИМ
#
import math
from collections import defaultdict
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model



class Command( NoArgsCommand ):

    #help = 'Import department from Sklad app to SHM  app.'
    requires_model_validation = True
    
    def handle_noargs(self, **options):
        from django.db.models import get_models
        # Выполнение всех операций в одной транзакции
        from django.db import transaction
        transaction.enter_transaction_management()
        try:
            transaction.managed(True)
            self.update_department()
            transaction.commit()
        finally:
            transaction.rollback()
            transaction.leave_transaction_management()     



    def update_department(self):    
        print "Update department list..."
        Department = get_model('shm', 'Department')

        for line in open("shm_department.csv"):
            uline = unicode(line, "CP1251").split(';', 5)
            name = uline[0]
            code = uline[1]
            id = uline[2]
            parent = uline[3]
            level = uline[4]

            if id == '':
                # Add new department
                print u'add    %s' % name
                #Department
                dept = Department(
                                parent = None,
                                level = 1,
                                name = name,
                                room = '',
                                #phone = None,
                                virtual = False,
                                code = code,
                                icon = '')
                dept.save()
                
            else: 
                # Update name of existing department
                print u'update %s' % name         
                dept = Department.objects.get(pk=id)
                dept.name = name
                dept.code = code
                dept.save()
                
                
#str = u'%s %s %s %s %s' % (uline[0],uline[1],uline[2],uline[3],uline[4])
#print str

#skiped = 0
#affected = 0 